class Order < ActiveRecord::Base
  PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order"]
  SHIPPING_TYPES = [ "Post"]
  
  has_many :line_items, dependent: :destroy
  
  attr_accessible :address, :email, :name, :pay_type, :shipping_type, :is_gift
  validates :name, :address, :email, presence: true
  validates :pay_type, inclusion: PAYMENT_TYPES 
  validates :shipping_type, inclusion: SHIPPING_TYPES
  
  validates_format_of :email, :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i
  
  def add_line_items_from_cart(cart)
    cart.line_items.each do |item|
      item.cart_id = nil
      line_items << item
    end
  end
  
  def total_price
    line_items.to_a.sum { |item| item.total_price }
  end
end
